//
//  UserAddressEditViewController.m
//  danpin
//
//  Created by chuangjia on 26/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "UserAddressEditViewController.h"
#import "ZToastManager.h"
#import "UIImageView+WebCache.h"
#import "ValidateShare.h"
#import "ZCameraICardController.h"

#define PROVINCE_COMPONENT  0
#define CITY_COMPONENT      1
#define DISTRICT_COMPONENT  2
@interface UserAddressEditViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate,ZCameraDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong) UITextField     *txtName;
@property(nonatomic,strong) UITextField     *txtPhone;
@property(nonatomic,strong) UITextField     *txtNumber;
@property(nonatomic,strong) UITextField     *txtAddress;

@property(nonatomic,strong) UIView *pView;
@property(nonatomic,strong) UIPickerView *picker;
@property(nonatomic,strong) NSDictionary *areaDic;
@property(nonatomic,strong) NSMutableArray *province;
@property(nonatomic,strong) NSArray *city;
@property(nonatomic,strong) NSArray *district;
@property(nonatomic,strong) NSString *provinceid;
@property(nonatomic,strong) NSString *cityid;
@property(nonatomic,strong) NSString *districtid;
@property(nonatomic,strong) NSString *provincename;
@property(nonatomic,strong) NSString *cityname;
@property(nonatomic,strong) NSString *districtname;


@property(nonatomic,assign) BOOL isnew;
@property(nonatomic,assign) BOOL isUpdateimage;

@property(nonatomic,strong) NSString *selectedProvince;
@property(nonatomic,strong) NSString *addressString;
@property(nonatomic,strong) NSMutableArray *imageArray;

@property(nonatomic,assign) BOOL is_card_face;
@property(nonatomic,assign) int provid;
@property(nonatomic,assign) int ciid;

@end

@implementation UserAddressEditViewController
@synthesize txtName = _txtName;
@synthesize txtPhone = _txtPhone;
@synthesize txtNumber = _txtNumber;
@synthesize txtAddress=_txtAddress;
@synthesize pView=_pView;
@synthesize picker=_picker;
@synthesize areaDic=_areaDic;
@synthesize province = _province;
@synthesize city=_city;
@synthesize district=_district;
@synthesize provinceid=_provinceid;
@synthesize cityid=_cityid;
@synthesize districtid=_districtid;
@synthesize provincename=_provincename;
@synthesize cityname=_cityname;
@synthesize districtname=_districtname;
@synthesize is_Default=_is_Default;
@synthesize isnew=_isnew;
@synthesize isUpdateimage=_isUpdateimage;

@synthesize selectedProvince=_selectedProvince;
@synthesize addressString=_addressString;
@synthesize imageArray=_imageArray;
@synthesize type =_type;
@synthesize addressDictionary=_addressDictionary;
@synthesize is_card_face=_is_card_face;
@synthesize provid=_provid;
@synthesize ciid=_ciid;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"编辑地址";
    self.rightTitle = @"保存";
    _addressString=@"  所在地";
    _is_card_face = YES;
    _isnew = NO;
    _isUpdateimage = NO;
    _provid=0;
    _ciid=0;
    [self initUI];
    if(_type==1)
    {
        [self getshopaddress];
    }
    
 
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer=nil;

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
        case 0:
        {
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 1:
        {
            if (_type==0) //新增
            {
                [self addshopaddress];
            }else //编辑
            {
                [self editshopaddress];
            }
        }
            break;
        default:
            break;
    }
}
-(void)dealloc
{
    self.imageArray =nil;
    self.addressString=nil;
    self.picker =nil;
    self.pView =nil;
    self.txtAddress=nil;
    self.txtName=nil;
    self.txtNumber=nil;
    self.txtPhone=nil;
    self.tbView = nil;
}

-(UITextField *)txtName
{
    if (!_txtName) {
        self.txtName = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtName.textColor =[UIColor lightGrayColor];
        [self.txtName setBorderStyle:UITextBorderStyleNone];
        self.txtName.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtName.font = FONT(13);
        self.txtName.placeholder =@"收件人 (必填)";
        self.txtName.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtName.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtName.returnKeyType = UIReturnKeyNext;
        self.txtName.keyboardType =UIKeyboardTypeDefault;
        self.txtName.delegate=self;
        [self.txtName setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtName setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtName;
}
-(UITextField *)txtPhone
{
    if (!_txtPhone) {
        self.txtPhone = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtPhone.textColor =[UIColor lightGrayColor];
        [self.txtPhone setBorderStyle:UITextBorderStyleNone];
        self.txtPhone.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtPhone.font = FONT(13);
        self.txtPhone.placeholder =@"联系电话 (必填)";
        self.txtPhone.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtPhone.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtPhone.returnKeyType = UIReturnKeyNext;
        self.txtPhone.keyboardType =UIKeyboardTypeNumberPad;
        self.txtPhone.delegate=self;
        [self.txtPhone setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtPhone setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtPhone;
}
-(UITextField *)txtNumber
{
    if (!_txtNumber) {
        self.txtNumber = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtNumber.textColor =[UIColor lightGrayColor];
        [self.txtNumber setBorderStyle:UITextBorderStyleNone];
        self.txtNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtNumber.font = FONT(13);
        self.txtNumber.placeholder =@"身份证号码 (必填)";
        self.txtNumber.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtNumber.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtNumber.returnKeyType = UIReturnKeyNext;
        self.txtNumber.keyboardType =UIKeyboardTypeDefault;
        self.txtNumber.delegate=self;
        [self.txtNumber setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtNumber setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtNumber;
}
-(UITextField *)txtAddress
{
    if (!_txtAddress) {
        self.txtAddress = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtAddress.textColor =[UIColor lightGrayColor];
        [self.txtAddress setBorderStyle:UITextBorderStyleNone];
        self.txtAddress.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtAddress.font = FONT(13);
        self.txtAddress.placeholder =@"详细地址";
        self.txtAddress.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtAddress.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtAddress.returnKeyType = UIReturnKeyDone;
        self.txtAddress.keyboardType =UIKeyboardTypeDefault;
        self.txtAddress.delegate=self;
        [self.txtAddress setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtAddress setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtAddress;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==_txtName) {
         [_txtPhone becomeFirstResponder];
    }else if (textField==_txtPhone)
    {
        [_txtNumber becomeFirstResponder];
    }
    else if (textField==_txtNumber)
    {
        [_txtAddress becomeFirstResponder];
    }
    else if (textField==_txtAddress)
    {
         [textField resignFirstResponder];
    }else{
         [textField resignFirstResponder];
    }
   
    return YES;
}
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0)
    {
        return 5;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 45;
    }
    else if (indexPath.section==1)
    {
        return 160;
    }
    else if (indexPath.section==2)
    {
        return 100;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@"userAddressEditViewCell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userAddressEditViewCell"];
        cell.textLabel.font = FONT(12);
        cell.textLabel.textColor = [UIColor lightGrayColor];
    }
    if (indexPath.section==0)
    {
        switch (indexPath.row) {
            case 0:
            {
                if (_type==1) {
                    if (_addressDictionary) {
                        self.txtName.text = [_addressDictionary objectForKey:@"real_name"];
                    }
                    
                }
                self.txtName.frame =CGRectMake(PHOTO_FRAME_WIDTH*2, 1, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*4, cell.frame.size.height);
                [cell addSubview:self.txtName];
                return cell;
            }
                break;
            case 1:
            {
                if (_type==1) {
                    if (_addressDictionary) {
                    self.txtPhone.text = [_addressDictionary objectForKey:@"phone"];
                    }
                }
                self.txtPhone.frame =CGRectMake(PHOTO_FRAME_WIDTH*2, 1, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*4, cell.frame.size.height);
                [cell addSubview:self.txtPhone];
                return cell;
            }
                break;
            case 2:
            {
                if (_type==1) {
                    if (_addressDictionary) {
                    self.txtNumber.text = [_addressDictionary objectForKey:@"id_card"];
                    }
                }
                self.txtNumber.frame =CGRectMake(PHOTO_FRAME_WIDTH*2, 1, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*4, cell.frame.size.height);
                [cell addSubview:self.txtNumber];
                return cell;
            }
                break;
            case 3:
            {
                if (_addressDictionary && !_isnew)
                {
                    self.provinceid = [_addressDictionary objectForKey:@"province_id"];
                    self.cityid = [_addressDictionary objectForKey:@"city_id"];
                    self.districtid = [_addressDictionary objectForKey:@"town_id"];
                    self.is_Default = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"is_default"]] replaceNullString];
                    self.provincename = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"province"]] replaceNullString];
                    self.cityname = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"city"]] replaceNullString];
                    self.districtname = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"town"]] replaceNullString];
                    
                    NSString *showMsg = [NSString stringWithFormat: @"%@ %@ %@", self.provincename, self.cityname, self.districtname];
                    _addressString = [NSString stringWithFormat:@"  所在地   %@",showMsg];
                }
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.textLabel.text = _addressString;
                return cell;
            }
                break;
            case 4:
            {
                if (_type==1) {
                    if (_addressDictionary) {
                    self.txtAddress.text = [_addressDictionary objectForKey:@"detail_address"];
                    }
                }
                self.txtAddress.frame =CGRectMake(PHOTO_FRAME_WIDTH*2, 1, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*4, cell.frame.size.height);
                [cell addSubview:self.txtAddress];
                return cell;
            }
                break;
            default:
                break;
        }
        return cell;
    }else if (indexPath.section==1)
    {
        
        UIView *numberView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 160)];
        numberView.backgroundColor=[UIColor clearColor];
        //
        UILabel *logLabel =[[UILabel alloc] initWithFrame:CGRectMake(20, 5, tableView.frame.size.width, 20)];
        logLabel.backgroundColor =[UIColor clearColor];
        logLabel.font = FONT(12);
        logLabel.textColor = [UIColor lightGrayColor];//UIColorFromRGB(0xcccccc);
        logLabel.textAlignment = NSTextAlignmentLeft;
        logLabel.text =@"身份证照片 (必须为收件人本人身份证)";
        [numberView addSubview:logLabel];
        logLabel=nil;
        //
        
        UIImageView *pic1 = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2-DEVICE_WIDTH/3)/2,30, DEVICE_WIDTH/3, 100)];
        pic1.tag =0;
        pic1.layer.borderColor =UIColorFromRGB(0xcccccc).CGColor;
        pic1.layer.borderWidth = 0.5f;
        if (_type==1) {
            if (_isUpdateimage) {
                if (_imageArray.count>0) {
                    if ((_imageArray.count==1 && _is_card_face)|| _imageArray.count>1) {
                        pic1.image =[_imageArray objectAtIndex:0] ;
                    }else{
                        [pic1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_front"]]]];
                    }
                }
            }else{
                
                [pic1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_front"]]]];
            }
        }else{
            if (_imageArray.count>0) {
                if ((_imageArray.count==1 && _is_card_face)|| _imageArray.count>1) {
                    pic1.image =[_imageArray objectAtIndex:0] ;
                }
                
            }
        }
        
        pic1.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(NumberAction:)];
        [pic1 addGestureRecognizer:singleTap1];
        [numberView addSubview:pic1];
        singleTap1=nil;
        UILabel *pic1Label =[[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width/2-100)/2, pic1.frame.origin.y+pic1.frame.size.height, 100, 20)];
        pic1Label.backgroundColor =[UIColor clearColor];
        pic1Label.font = FONT(12);
        pic1Label.textColor =UIColorFromRGB(0xcccccc);
        pic1Label.textAlignment = NSTextAlignmentCenter;
        pic1Label.text =@"正面";
        [numberView addSubview:pic1Label];
        pic1Label=nil;
        //
        UIImageView *pic2 = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2+(self.view.frame.size.width/2-DEVICE_WIDTH/3)/2,30, DEVICE_WIDTH/3, 100)];
        pic2.tag =1;
        pic2.layer.borderColor =UIColorFromRGB(0xcccccc).CGColor;
        pic2.layer.borderWidth = 0.5f;
        if (_type ==1 ) {
            if (_isUpdateimage) {
                if (_imageArray.count>1) {
                    if ((_imageArray.count==1 && !_is_card_face)|| _imageArray.count>1) {
                        pic2.image =[_imageArray objectAtIndex:1] ;
                    }else{
                        
                        [pic2 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_behind"]]]];
                    }
                }
            }else{
                [pic2 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_behind"]]]];
            }
        }else
        {
            if (_imageArray.count>1) {
                if ((_imageArray.count==1 && !_is_card_face)|| _imageArray.count>1) {
                    pic2.image =[_imageArray objectAtIndex:1] ;
                }
            }
        }
        
        pic2.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(NumberAction:)];
        [pic2 addGestureRecognizer:singleTap2];
        [numberView addSubview:pic2];
        singleTap2=nil;
        UILabel *pic2Label =[[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2+(self.view.frame.size.width/2-100)/2, pic2.frame.origin.y+pic2.frame.size.height, 100, 20)];
        pic2Label.backgroundColor =[UIColor clearColor];
        pic2Label.font = FONT(12);
        pic2Label.textColor =UIColorFromRGB(0xcccccc);
        pic2Label.textAlignment = NSTextAlignmentCenter;
        pic2Label.text =@"反面";
        [numberView addSubview:pic2Label];
        pic2Label=nil;
        
        
        UILabel *Label =[[UILabel alloc] initWithFrame:CGRectMake(1, pic2.frame.size.height - 12, pic2.frame.size.width-1, 12)];
        Label.backgroundColor =[UIColor grayColor];
        Label.alpha = 0.75f;
        Label.font = FONT(10);
        Label.textColor =UIColorFromRGB(0xcccccc);
        Label.textAlignment = NSTextAlignmentCenter;
        Label.text =@"仅清关用";
        [pic2 addSubview:Label];
        Label=nil;
        
        Label =[[UILabel alloc] initWithFrame:CGRectMake(1, pic1.frame.size.height - 12, pic1.frame.size.width-1, 12)];
        Label.backgroundColor =[UIColor grayColor];
        Label.alpha = 0.75f;
        Label.font = FONT(10);
        Label.textColor =UIColorFromRGB(0xcccccc);
        Label.textAlignment = NSTextAlignmentCenter;
        Label.text =@"仅清关用";
        [pic1 addSubview:Label];
        Label=nil;
        
        //
        [cell addSubview:numberView];
        numberView=nil;
    }
    else
    {
        
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.text = @" - 身份证仅作为海关清关用途。\n - 如您现在手边没有身份证照片，可于下单后24小时内到此补充身份证照片。\n - 身份证照片必须完整、清晰，以便海关蜀黍查验。";
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
        if (indexPath.row==3) {
             [self.txtName resignFirstResponder];
             [self.txtPhone resignFirstResponder];
             [self.txtNumber resignFirstResponder];
             [self.txtAddress resignFirstResponder];
            [self showPickerView];
        }
    }
}

//
-(void)showPickerView
{
    [self hiddenPickerView];
    [self initpickviewData];
    _pView =[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-260, self.view.frame.size.width, 260)];
    _pView.backgroundColor=[UIColor whiteColor];
    UIView *toolbar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    toolbar.backgroundColor =UIColorFromRGB(0xe5e5e5);
    toolbar.layer.borderColor = UIColorFromRGB(0xe5e5e5).CGColor;
    toolbar.layer.borderWidth =1;
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 10, 40, 20);
    backButton.tag =0;
    [backButton setTitleColor:UIColorFromRGB(0x285790) forState:UIControlStateNormal];
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(pickAction:) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:backButton];
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    okButton.frame = CGRectMake(self.view.frame.size.width-50,10, 40, 20);
    okButton.tag =1;
    [okButton setTitleColor:UIColorFromRGB(0x285790) forState:UIControlStateNormal];
    [okButton setTitle:@"确定" forState:UIControlStateNormal];
    [okButton addTarget:self action:@selector(pickAction:) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:okButton];
    [_pView addSubview:toolbar];
    toolbar=nil;

    _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,40, self.view.frame.size.width, 220)];
    // 显示选中框
    _picker.showsSelectionIndicator=YES;
    _picker.dataSource = self;
    _picker.delegate = self;
    [_pView addSubview:_picker];
    [self.view addSubview:_pView];

    
    [ _picker selectRow:_provid inComponent:PROVINCE_COMPONENT animated:YES];
    [ _picker selectRow:_ciid inComponent:CITY_COMPONENT animated:YES];
    
    
  
}
-(void)hiddenPickerView
{
    if (_picker) {
        _picker.dataSource=nil;
        _picker.delegate=nil;
        [_picker removeFromSuperview];
        _picker=nil;
    }
    if (self.pView) {
        [self.pView removeFromSuperview];
        self.pView=nil;
    }
}
-(void)pickAction:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            [self hiddenPickerView];
        }
            break;
        case 1:
        {
            _isnew = YES;
            NSInteger provinceIndex = [_picker selectedRowInComponent: PROVINCE_COMPONENT];
            NSInteger cityIndex = [_picker selectedRowInComponent: CITY_COMPONENT];
            NSInteger districtIndex = [_picker selectedRowInComponent: DISTRICT_COMPONENT];
            
            self.provincename = [[_province objectAtIndex: provinceIndex] objectForKey:@"name"];
            self.cityname = [[_city objectAtIndex: cityIndex] objectForKey:@"name"];
            self.districtname = [[_district objectAtIndex:districtIndex] objectForKey:@"name"];
            self.provinceid = [[_province objectAtIndex: provinceIndex] objectForKey:@"id"];
            self.cityid = [[_city objectAtIndex: cityIndex] objectForKey:@"id"];
            self.districtid = [[_district objectAtIndex:districtIndex] objectForKey:@"id"];
            
            if ([self.provincename isEqualToString: self.cityname] && [self.cityname isEqualToString: self.districtname]) {
                self.cityname = @"";
                self.districtname = @"";
            }
            else if ([self.cityname isEqualToString: self.districtname]) {
                self.districtname= @"";
            }
            NSString *showMsg = [NSString stringWithFormat: @"%@ %@ %@.", self.provincename, self.cityname, self.districtname];
            self.addressString = [NSString stringWithFormat:@"  所在地   %@",showMsg];
            [self.tbView reloadData];
            [self hiddenPickerView];
        }
            break;
        default:
            break;
    }
}
#pragma method pickview
-(void)initpickviewData
{
    _province =nil;
    _city=nil;
    _district=nil;
    _areaDic=nil;
    _provinceid=nil;
    _cityid=nil;
    _districtid=nil;
    _selectedProvince=nil;
    if (!_province) {
        _province = [[NSMutableArray alloc] init];
    }
    
     _province = [ZShare sharedInstance].addressInfoDictionary;
    if (_province==nil || _province.count==0) {
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"address" ofType:@"plist"];
        NSMutableArray *area = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        _province= area;
    }
    NSDictionary *pro =[ZShare sharedInstance].ipAddress;
    NSString *paovince_id=@"";
    NSString *city_id=@"";
    if (pro) {
        paovince_id = [[NSString stringWithFormat:@"%@",[pro objectForKey:@"paovince_id"]] replaceNullString];
        city_id = [[NSString stringWithFormat:@"%@",[pro objectForKey:@"city_id"]] replaceNullString];
    }
    _provid = [self provinceIndex:_province pid:paovince_id];
    
    _selectedProvince = [[_province objectAtIndex:_provid] objectForKey:@"name"];
 
   if (!_city) {
        _city = [[NSMutableArray alloc] init];
    }
    NSDictionary *city = [_province objectAtIndex:_provid];
    _city = [city objectForKey:@"city"];
    _ciid =[self provinceIndex:_city pid:city_id];
    
    if (!_district) {
        _district = [[NSMutableArray alloc] init];
    }
    NSDictionary *town = [_city objectAtIndex:0];
    _district = [town objectForKey:@"town"];
 
}
-(int)provinceIndex:(NSArray *)array pid:(NSString*)pid
{
    int index =0;
    for (int i=0; i<array.count; i++) {
        NSDictionary *prov = [array objectAtIndex:i];
        NSString *tpid = [prov objectForKey:@"id"];
        if ([tpid isEqualToString:pid]) {
            index = i;
            break;
        }
        
    }
    return index;
}
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == PROVINCE_COMPONENT) {
        return [_province count];
    }
    else if (component == CITY_COMPONENT) {
        return [_city count];
    }
    else {
        return [_district count];
    }
}
//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == PROVINCE_COMPONENT) {
        return [_province objectAtIndex: row];
    }
    else if (component == CITY_COMPONENT) {
        return [_city objectAtIndex: row];
    }
    else {
        return [_district objectAtIndex: row];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == PROVINCE_COMPONENT) {
        _selectedProvince = [[_province objectAtIndex: row] objectForKey:@"name"];
        if (!_city) {
            _city = [[NSMutableArray alloc] init];
        }
        NSDictionary *city = [_province objectAtIndex:row];
        _city = [city objectForKey:@"city"];
        
        if (!_district) {
            _district = [[NSMutableArray alloc] init];
        }
        NSDictionary *town = [_city objectAtIndex:0];
        _district = [town objectForKey:@"town"];
        
        [_picker selectRow: 0 inComponent: CITY_COMPONENT animated: YES];
        [_picker selectRow: 0 inComponent: DISTRICT_COMPONENT animated: YES];
        [_picker reloadComponent: CITY_COMPONENT];
        [_picker reloadComponent: DISTRICT_COMPONENT];
        
    }
    else if (component == CITY_COMPONENT) {
        
        if (!_district) {
            _district = [[NSMutableArray alloc] init];
        }
        NSDictionary *town = [_city objectAtIndex:row];
        _district = [town objectForKey:@"town"];
        
        
        [_picker selectRow: 0 inComponent: DISTRICT_COMPONENT animated: YES];
        [_picker reloadComponent: DISTRICT_COMPONENT];
    }
    
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == PROVINCE_COMPONENT) {
        return 80;
    }
    else if (component == CITY_COMPONENT) {
        return 100;
    }
    else {
        return 115;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *myView = nil;
    
    if (component == PROVINCE_COMPONENT) {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 78, 30)];
        myView.textAlignment = NSTextAlignmentCenter;
        myView.text = [[_province objectAtIndex:row] objectForKey:@"name"];
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    else if (component == CITY_COMPONENT) {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 95, 30)] ;
        myView.textAlignment = NSTextAlignmentCenter;
        myView.text = [[_city objectAtIndex:row] objectForKey:@"name"];
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    else {
        myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 110, 30)];
        myView.textAlignment = NSTextAlignmentCenter;
        myView.text = [[_district objectAtIndex:row] objectForKey:@"name"];
        myView.font = [UIFont systemFontOfSize:14];
        myView.backgroundColor = [UIColor clearColor];
    }
    
    return myView;
}
//
-(void)NumberAction:(UITapGestureRecognizer * )recognizer
{
    switch (recognizer.view.tag) {
        case 0:
        {
             self.is_card_face = YES;
        }break;
        case 1:
        {
             self.is_card_face = NO;
        }
            break;
        default:
            break;
    }
    [self.txtName resignFirstResponder];
    [self.txtPhone resignFirstResponder];
    [self.txtNumber resignFirstResponder];
    [self.txtAddress resignFirstResponder];
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}
#pragma usericon
//

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:  //打开照相机拍照
        {
            ZCameraICardController *icard = [[ZCameraICardController alloc] init];
            icard.delegate=self;
            icard.isFront = self.is_card_face;
            [self presentViewController:icard animated:YES completion:nil];
//             [self takePhoto];
        }
           
            break;
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}
-(void)cameraDidTakePhoto:(UIImage *)image
{
    [self dismissViewControllerAnimated:YES completion:nil];
    //图片保存的路径
    if (!_imageArray) {
        _imageArray=[[NSMutableArray alloc] init];
    }
    _isUpdateimage = YES;
//    NSData * imageData = UIImageJPEGRepresentation(image,1);
//    float length = [imageData length]/1024;
//    NSLog(@"===========%f",length);
    [_imageArray addObject:image];
    [self.tbView reloadData];
    [self upLoadIcon:_imageArray];
}
-(void)cameraDidCancel
{
     [self dismissViewControllerAnimated:YES completion:nil];
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        DLog(@"模拟其中无法打开照相机,请在真机中使用");
        
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* imageo = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        if (imageo==nil) {
            imageo = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        }
     
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *image = [self scaleImage:imageo toScale:0.1];
//        NSData * imageData = UIImageJPEGRepresentation(image,1);
//
//        float length = [imageData length]/1024;
//        NSLog(@"===========%f",length);
//       
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        //图片保存的路径
        if (!_imageArray) {
            _imageArray=[[NSMutableArray alloc] init];
        }
         _isUpdateimage = YES;
        [_imageArray addObject:image];
        [self.tbView reloadData];
        [self upLoadIcon:_imageArray];
    }
}

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    DLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)upLoadIcon:(NSMutableArray*)imageArray
{
    if (imageArray.count==0) {
        return;
    }
    [WTStatusBar setStatusText:@"图片上传中..." animated:YES];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    if (_is_card_face) {
        [dict setValue:@"front" forKey:@"id_card_face"];
    }else{
        [dict setValue:@"behind" forKey:@"id_card_face"];
    }
    _isUpdateimage = YES;
//    __weak typeof (self) wSelf = self;
    [BaseModel uploadIdCard:dict images:imageArray success:^(AFHTTPRequestOperation *operation, id result) {
        if (result==nil) {
            [[ZToastManager ShardInstance] hideprogress];
            [WTStatusBar clearStatusAnimated:YES];
            return;
        }
        if (result && [result isKindOfClass:[NSDictionary class]])
        {
            
            [WTStatusBar setStatusText:[NSString stringWithFormat:@"%@",[result objectForKey:@"msg"]] animated:YES];
            [WTStatusBar clearStatusAnimated:YES];
        }
    } failure:^(NSError *error)
    {
        [WTStatusBar setStatusText:@"上传失败..." animated:YES];
        [WTStatusBar clearStatusAnimated:YES];
    } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        if (totalBytesExpectedToWrite>0&&totalBytesWritten>0) {
            CGFloat process = (CGFloat)((totalBytesWritten*100)/totalBytesExpectedToWrite);
            [WTStatusBar setProgress:process/100 animated:YES];
            if (process>=100) {
                  [WTStatusBar clearStatusAnimated:YES];
            }
        }
    }];
}
//======================
//
//=======================
//修改地址
-(void)getshopaddress
{
    [ZShare showAnimationView:self.view center:CGPointZero];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[_addressDictionary objectForKey:@"id"] forKey:@"id"];
    __weak typeof (self) wSelf = self;
    [BaseModel getShopAddressById:dict success:^(AFHTTPRequestOperation *operation, id result) {
        if (result&&[result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDist =(NSDictionary*)result;
//            NSLog(@"%@",resultDist);
            id data =  [resultDist objectForKey:@"row"];
            if (data && [data isKindOfClass:[NSDictionary class]]){
                 _addressDictionary =[NSMutableDictionary dictionaryWithDictionary:data] ;
            }
            [_tbView reloadData];
        }
        [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view];
    }];
}
//添加地址
-(void)addshopaddress
{
    if (self.txtName.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人姓名"];
        return;
    }
    if (self.txtPhone.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人手机号"];
        return;
    }
    if (self.txtNumber.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人身份证号码"];
        return;
    }
    if (![ValidateShare checkUserIDCardNumber:self.txtNumber.text]) {
        [[ZToastManager ShardInstance] showtoast:@"请输入有效身份证号码"];
        return;
    }
    if (self.addressString.length==0 ||[self.addressString isEqualToString:@"  所在地"]) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人所在地"];
        return;
    }
    if (self.txtAddress.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人详细地址"];
        return;
    }
     NSMutableDictionary *dict =[NSMutableDictionary dictionary];
     [dict setValue:self.txtName.text forKey:@"real_name"];
     [dict setValue:self.txtPhone.text forKey:@"phone"];
     [dict setValue:self.txtNumber.text forKey:@"id_card"];
     [dict setValue:@"" forKey:@"id_card_front"];
     [dict setValue:@"" forKey:@"id_card_behind"];
     [dict setValue:self.provinceid forKey:@"province_id"];
     [dict setValue:self.cityid forKey:@"city_id"];
     [dict setValue:self.districtid forKey:@"town_id"];
     [dict setValue:self.provincename forKey:@"province"];
     [dict setValue:self.cityname forKey:@"city"];
     [dict setValue:self.districtname forKey:@"town"];
     [dict setValue:self.is_Default forKey:@"is_default"];
   
     [dict setValue:self.txtAddress.text forKey:@"detail_address"];
    [[ZToastManager ShardInstance] showprogress];
    __weak typeof (self) wSelf = self;
    [BaseModel addShopAddress:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [[ZToastManager ShardInstance] hideprogress];
        [wSelf parserResultObject:result];
    } failure:^(NSError *error) {
      [[ZToastManager ShardInstance] hideprogress];
    }];
}
-(void)editshopaddress
{
    if (self.txtName.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人姓名"];
        return;
    }
    if (self.txtPhone.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人手机号"];
        return;
    }
    if (self.txtNumber.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人身份证号码"];
        return;
    }
    if (![ValidateShare checkUserIDCardNumber:self.txtNumber.text]) {
         [[ZToastManager ShardInstance] showtoast:@"请输入有效身份证号码"];
        return;
    }
    if (self.addressString.length==0||[self.addressString isEqualToString:@"  所在地"]) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人所在地"];
        return;
    }
    if (self.txtAddress.text.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请输入收件人详细地址"];
        return;
    }
   
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[_addressDictionary objectForKey:@"id"] forKey:@"id"];
    [dict setValue:self.txtName.text forKey:@"real_name"];
    [dict setValue:self.txtPhone.text forKey:@"phone"];
    [dict setValue:self.txtNumber.text forKey:@"id_card"];
    NSString *id_card_front = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_front"]] replaceNullString];
    NSString *id_card_behind = [[NSString stringWithFormat:@"%@",[_addressDictionary objectForKey:@"id_card_behind"]] replaceNullString];
    [dict setValue:id_card_front forKey:@"id_card_front"];
    [dict setValue:id_card_behind forKey:@"id_card_behind"];
    [dict setValue:self.provinceid forKey:@"province_id"];
    [dict setValue:self.cityid forKey:@"city_id"];
    [dict setValue:self.districtid forKey:@"town_id"];
    [dict setValue:self.provincename forKey:@"province"];
    [dict setValue:self.cityname forKey:@"city"];
    [dict setValue:self.districtname forKey:@"town"];
    [dict setValue:self.txtAddress.text forKey:@"detail_address"];
    [dict setValue:self.is_Default forKey:@"is_default"];
    [[ZToastManager ShardInstance] showprogress];
     __weak typeof (self) wSelf = self;
    [BaseModel editShopAddress:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [[ZToastManager ShardInstance] hideprogress];
        [wSelf parserResultObject:result];
    } failure:^(NSError *error) {
        [[ZToastManager ShardInstance] hideprogress];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [[ZToastManager ShardInstance] hideprogress];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        int data =  [[resultObject objectForKey:@"code"] intValue];
        NSString *msg =  [resultObject objectForKey:@"msg"];
        [[ZToastManager ShardInstance] showtoast:msg];
        if (data==1) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateAddressList" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
       
    }
}


-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    [self hideKeyboard];
}

- (void) hideKeyboard
{
    if(_txtName.isFirstResponder)
    {
        [_txtName resignFirstResponder];
    }
    if(_txtPhone.isFirstResponder)
    {
        [_txtPhone resignFirstResponder];
    }
    if(_txtNumber.isFirstResponder)
    {
        [_txtNumber resignFirstResponder];
    }
    if(_txtAddress.isFirstResponder)
    {
        [_txtAddress resignFirstResponder];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self hideKeyboard];
}


@end
